package warehouse

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"insighttracking/apps/admin/auth"
	"insighttracking/query/bo"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type ModifyByIdApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewModifyByIdApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *ModifyByIdApiLogic {
	hostname, _ := os.Hostname()
	return &ModifyByIdApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *ModifyByIdApiLogic) ModifyByIdApi(req *types.ModifyWarehouseReq) (resp string, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return "", err
	}
	if req.Status == 1 && req.IsDefault == 1 {
		return "", errors.New("该仓库已禁用/默认仓不可禁用")
	}
	if req.IsDefault == 0 {
		warehouseEntity, err := service.WarehouseService.GetWarehouseByEnterpriseDefaultIdApi(l.ctx, accountInfo.EnterpriseId)
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return "", errors.New("默认仓库不存在")
		}
		if warehouseEntity.ID == req.Id {
			return "", errors.New("一个企业必须要有一个默认仓库")
		}
	}

	if err = service.WarehouseService.ModifyByIdApi(l.ctx, req.Id, bo.CreateWarehouseBo{
		Name:         req.Name,      // 仓库名称
		Code:         req.Code,      // 仓库编码
		Status:       req.Status,    // 状态0表示正常,1表示禁用
		IsDefault:    req.IsDefault, // 是否为默认仓库,0表示不是，1表示是
		PersonID:     req.PersonID,  // 仓库负责人,关联到enterprise_person表主键id
		Describe:     req.Describe,  // 仓库名称描述
		EnterpriseId: accountInfo.EnterpriseId,
	}); err != nil {
		return "", err
	}
	return "操作成功", nil
}
